package me.dwliu.ebase.modules.gen.service;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import me.dwliu.ebase.modules.gen.entity.ColumnDTO;
import me.dwliu.ebase.modules.gen.entity.ColumnEntity;
import me.dwliu.ebase.modules.gen.entity.TableDTO;
import me.dwliu.ebase.modules.gen.entity.TableEntity;
import me.dwliu.ebase.modules.gen.exception.CustomException;
import me.dwliu.ebase.modules.gen.util.FreeMarkerTemplateUtils;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.WordUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 *
 * @author liudw
 * @date 2020/8/23 20:18
 **/
@Slf4j
@Component
public class CodeGenService {

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;

    public static final String TEMPLATE_FILE_NAME_DO_JAVA = "DO.java.ftl";
    public static final String TEMPLATE_FILE_NAME_DTO_JAVA = "DTO.java.ftl";
    public static final String TEMPLATE_FILE_NAME_EXCEL_JAVA = "Excel.java.ftl";
    public static final String TEMPLATE_FILE_NAME_DAO_JAVA = "DAO.java.ftl";
    public static final String TEMPLATE_FILE_NAME_DAO_XML = "DAO.xml.ftl";
    public static final String TEMPLATE_FILE_NAME_SERVICE_JAVA = "Service.java.ftl";
    public static final String TEMPLATE_FILE_NAME_SERVICE_IMPL_JAVA = "ServiceImpl.java.ftl";
    public static final String TEMPLATE_FILE_NAME_CONTROLLER_JAVA = "Controller.java.ftl";
    // public static final String TEMPLATE_FILE_NAME_MENU_SQL = "menu.sql.ftl";
    public static final String TEMPLATE_FILE_NAME_MENU_MYSQL_SQL = "menu_mysql.sql.ftl";
    public static final String TEMPLATE_FILE_NAME_MENU_ORACLE_SQL = "menu_oracle.sql.ftl";
    public static final String TEMPLATE_FILE_NAME_MENU_SQLSERVER_SQL = "menu_sqlserver.sql";
    public static final String TEMPLATE_FILE_NAME_MENU_POSTGRESQL_SQL = "menu_postgresql.sql";
    public static final String TEMPLATE_FILE_NAME_INDEX_VUE = "index.vue.ftl";
    public static final String TEMPLATE_FILE_NAME_API_JS = "api.js.ftl";


    public List<String> getTemplates() {
        List<String> templates = new ArrayList<>();
        templates.add(TEMPLATE_FILE_NAME_DO_JAVA);
        templates.add(TEMPLATE_FILE_NAME_DTO_JAVA);
        templates.add(TEMPLATE_FILE_NAME_EXCEL_JAVA);
        templates.add(TEMPLATE_FILE_NAME_DAO_JAVA);
        templates.add(TEMPLATE_FILE_NAME_DAO_XML);
        templates.add(TEMPLATE_FILE_NAME_SERVICE_JAVA);
        templates.add(TEMPLATE_FILE_NAME_SERVICE_IMPL_JAVA);
        templates.add(TEMPLATE_FILE_NAME_CONTROLLER_JAVA);
        templates.add(TEMPLATE_FILE_NAME_INDEX_VUE);
        templates.add(TEMPLATE_FILE_NAME_API_JS);

        if (StringUtils.equals(driverClassName, "com.mysql.jdbc.Driver")
                || StringUtils.equals(driverClassName, "com.mysql.cj.jdbc.Driver")) {
            templates.add(TEMPLATE_FILE_NAME_MENU_MYSQL_SQL);
        } else if (StringUtils.equals(driverClassName, "oracle.jdbc.OracleDriver")) {
            templates.add(TEMPLATE_FILE_NAME_MENU_ORACLE_SQL);
        } else if (StringUtils.equals(driverClassName, "com.microsoft.sqlserver.jdbc.SQLServerDriver")) {
            templates.add(TEMPLATE_FILE_NAME_MENU_SQLSERVER_SQL);
        } else if (StringUtils.equals(driverClassName, "org.postgresql.Driver")) {
            templates.add(TEMPLATE_FILE_NAME_MENU_POSTGRESQL_SQL);
        }


        return templates;
    }

    /**
     * 数据表转换
     *
     * @param table         数据库表信息
     * @param columns       数据库表字段信息集合
     * @param config        属性配置
     * @param hasBigDecimal 是否有BigDecimal
     * @return
     */
    private TableDTO translateEntity(TableEntity table, List<ColumnEntity> columns, Configuration config, boolean hasBigDecimal) {

        //表信息
        TableDTO tableDTO = new TableDTO();
        tableDTO.setTableName(table.getTableName());
        tableDTO.setTableComment(table.getTableComment());
        //表名转换成Java类名
        String className = tableToJava(tableDTO.getTableName(), config.getString("tablePrefix"));
        tableDTO.setClassName(className);
        tableDTO.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnDTO> columsList = new ArrayList<>();
        for (ColumnEntity column : columns) {
            ColumnDTO columnEntity = new ColumnDTO();
            columnEntity.setColumnName(column.getColumnName());
            columnEntity.setDataType(column.getDataType());
            columnEntity.setComment(column.getColumnComment());
            columnEntity.setExtra(column.getExtra());

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setPropName(attrName);
            columnEntity.setPropname(StringUtils.uncapitalize(attrName));

            String attrType = null;


            //针对 ORACLE 定制
            if (StringUtils.equals("NUMBER", columnEntity.getDataType())) {
                BigDecimal dataPrecision = column.getDataPrecision();
                BigDecimal dataScale = column.getDataScale();
                //有小数位
                if (dataScale.intValue() != 0) {
                    attrType = "Double";
                } else {
                    if (dataPrecision.intValue() > 16) {
                        attrType = "Long";
                    } else {
                        attrType = "Integer";
                    }

                }
            } else {
                //列的数据类型，转换成Java类型
                attrType = config.getString(columnEntity.getDataType(), "unknowType");
            }


            columnEntity.setPropType(attrType);
            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }
            //是否主键
            if ("PRI".equalsIgnoreCase(column.getColumnKey()) && tableDTO.getPk() == null) {
                tableDTO.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableDTO.setClassProps(columsList);

        return tableDTO;
    }

    /**
     * 生成模板代码
     *
     * @param tableDTO      数据库表信息
     * @param config        属性配置
     * @param hasBigDecimal 是否有BigDecimal
     * @return
     */
    private List<Map<String, String>> generateTemplateCode(TableDTO tableDTO, Configuration config, boolean hasBigDecimal) {


        //没主键，则第一个字段为主键
        if (tableDTO.getPk() == null) {
            tableDTO.setPk(tableDTO.getClassProps().get(0));
        }

        String mainPath = config.getString("mainPath");
        mainPath = StringUtils.isBlank(mainPath) ? "XXX" : mainPath;
        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableDTO.getTableName());
        map.put("comments", tableDTO.getTableComment());
        map.put("pk", tableDTO.getPk());
        map.put("className", tableDTO.getClassName());
        map.put("classname", tableDTO.getClassname());
        map.put("pathName", tableDTO.getClassname().toLowerCase());
        map.put("columns", tableDTO.getClassProps());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("mainPath", mainPath);
        map.put("package", config.getString("package"));
        map.put("moduleName", config.getString("moduleName"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //获取模板列表
        List<String> templates = getTemplates();

        List<Map<String, String>> templateCodes = new ArrayList<>();

        for (String template : templates) {
            Map<String, String> templateCodeMap = new HashMap<>();
            templateCodeMap.put("template", template);
            //渲染模板
            Template tpl = null;
            try {
                tpl = FreeMarkerTemplateUtils.getTemplate(template);
            } catch (IOException e) {
                e.printStackTrace();
            }

            StringWriter sw = new StringWriter();
            try {
                tpl.process(map, sw);
                sw.flush();
                templateCodeMap.put("templateCode", sw.toString());
                templateCodes.add(templateCodeMap);
            } catch (TemplateException | IOException e) {
                e.printStackTrace();
            }

        }

        return templateCodes;
    }

    /**
     * 生成代码
     *
     * @param table   数据库表信息
     * @param columns 数据库表字段信息集合
     * @param zip
     * @throws IOException
     */
    public void generatorCode(TableEntity table, List<ColumnEntity> columns, ZipOutputStream zip) throws IOException {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        TableDTO tableDTO = translateEntity(table, columns, config, hasBigDecimal);
        List<Map<String, String>> templateCodes = generateTemplateCode(tableDTO, config, hasBigDecimal);

        templateCodes.stream().forEach(p -> {
            String template = p.get("template");
            String templateCode = p.get("templateCode");
            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableDTO.getClassName(), config.getString("package"), config.getString("moduleName"))));
                IOUtils.write(templateCode.toString(), zip, "UTF-8");
                zip.closeEntry();
            } catch (Exception e) {
                throw new CustomException("渲染模板失败，表名：" + tableDTO.getTableName(), e);
            }
        });
    }

    /**
     * 预览
     *
     * @param table
     * @param columns
     * @return
     */
    public List<Map<String, String>> previewTemplateCode(TableEntity table, List<ColumnEntity> columns) {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        TableDTO tableDTO = translateEntity(table, columns, config, hasBigDecimal);
        List<Map<String, String>> templateCodes = generateTemplateCode(tableDTO, config, hasBigDecimal);

        return templateCodes;
    }

    /**
     * 列名转换成Java属性名
     */
    public String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public Configuration getConfig() {
        try {
            Configurations configurations = new Configurations();
            PropertiesConfiguration properties = configurations.properties(new File("generator.properties"));
            return properties;
        } catch (ConfigurationException e) {
            throw new CustomException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public String getFileName(String template, String className, String packageName, String moduleName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }

        if (template.contains(TEMPLATE_FILE_NAME_DO_JAVA)) {
            return packagePath + File.separator + "entity" + File.separator + className + "DO.java";
        }

        if (template.contains(TEMPLATE_FILE_NAME_DTO_JAVA)) {
            return packagePath + File.separator + "dto" + File.separator + className + "DTO.java";
        }

        if (template.contains(TEMPLATE_FILE_NAME_EXCEL_JAVA)) {
            return packagePath + File.separator + "excel" + File.separator + className + "Excel.java";
        }
        if (template.contains(TEMPLATE_FILE_NAME_DAO_JAVA)) {
            return packagePath + "dao" + File.separator + className + "DAO.java";
        }

        if (template.contains(TEMPLATE_FILE_NAME_DAO_XML)) {
            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + moduleName + File.separator + className + "DAO.xml";
        }

        if (template.contains(TEMPLATE_FILE_NAME_SERVICE_JAVA)) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if (template.contains(TEMPLATE_FILE_NAME_SERVICE_IMPL_JAVA)) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains(TEMPLATE_FILE_NAME_CONTROLLER_JAVA)) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }

        if (template.contains(TEMPLATE_FILE_NAME_MENU_MYSQL_SQL) ||
                template.contains(TEMPLATE_FILE_NAME_MENU_ORACLE_SQL) ||
                template.contains(TEMPLATE_FILE_NAME_MENU_SQLSERVER_SQL) ||
                template.contains(TEMPLATE_FILE_NAME_MENU_POSTGRESQL_SQL)) {
            return className.toLowerCase() + "_menu.sql";
        }

        if (template.contains(TEMPLATE_FILE_NAME_INDEX_VUE)) {
            return className.toLowerCase() + ".vue";
        }

        if (template.contains(TEMPLATE_FILE_NAME_API_JS)) {
            return className.toLowerCase() + ".js";
        }

        if (template.contains("index.vue.vm")) {
            return "main" + File.separator + "resources" + File.separator + "elementui" + File.separator + "src" + File.separator + "views" +
                    File.separator + className.toLowerCase() + File.separator + "index.vue";
        }

        if (template.contains("add-or-update.vue.vm")) {
            return "main" + File.separator + "resources" + File.separator + "elementui" + File.separator + "src" + File.separator + "views" +
                    File.separator + className.toLowerCase() + File.separator + "add-or-update.vue";
        }

        if (template.contains("index.js.vm")) {
            return "main" + File.separator + "resources" + File.separator + "elementui" + File.separator + "src" + File.separator + "api" +
                    File.separator + "modules" + File.separator + className.toLowerCase() + ".js";
        }

        return null;
    }


}
